import React, { useState } from 'react'
import useDialogState from '@/hooks/use-dialog-state'
import { type DictItem } from '../data/schema'

type DictsDialogType = 'add' | 'edit' | 'delete'

interface DictsContextType {
  open: DictsDialogType | null
  setOpen: (str: DictsDialogType | null) => void
  currentRow: DictItem | null
  setCurrentRow: React.Dispatch<React.SetStateAction<DictItem | null>>
}

const DictsContext = React.createContext<DictsContextType | null>(null)

interface Props {
  children: React.ReactNode
}

export default function DictsProvider({ children }: Props) {
  const [open, setOpen] = useDialogState<DictsDialogType>(null)
  const [currentRow, setCurrentRow] = useState<DictItem | null>(null)

  return (
    <DictsContext.Provider value={{ open, setOpen, currentRow, setCurrentRow }}>
      {children}
    </DictsContext.Provider>
  )
}

// eslint-disable-next-line react-refresh/only-export-components
export const useDictsContext = () => {
  const dictsContext = React.useContext(DictsContext)

  if (!dictsContext) {
    throw new Error('useDictsContext has to be used within <DictsContext>')
  }

  return dictsContext
}